#include <iostream>
#include <string>
#include "Protocol.hpp"
#include "Calculator.hpp"
#include "connection.hpp"
#include "Log.hpp"
using namespace Protocol;
using namespace CalCulateNS;

class HandlerRequest
{
public:
    void Handler(Connection::ptr conn)
    {
        std::string message;
        while (Decode(conn->Inbuffer(), &message))
        {
            // 1.创建request对象
            Factory factory;
            auto req = factory.BuildRequest();
            // 2.反序列化
            if (!req->Deserialize(message))
            {
                lg(Warning, "Deserialize failed");
                return;
            }
            // 3.业务处理
            auto resp = cal.Cal(req);
            // 4.序列化
            std::string out;
            resp->Serialize(&out);
            // 5.封装完整报文
            std::string buffer = Encode(out);
            // 6.追加到outbuffer
            conn->AddOutBuffer(buffer);
            // 7.发送报文给客户端
            if (!conn->OutBufferEmpty())
            {
                conn->_sender(conn);
            }
        }
    }
private:
    Calculate cal;
};
